const Response = require('../utils/response');

//日志
const {
    logger
} = require('../config/logger');

//获取IP
const {
    clientIp
} = require('../utils/getIp');

//解密token
const {
    token_verify
} = require('../config/jwt_admin');

//载入路由白名单
const whiteList_admin = require("../interceptor/whiteList_admin.js");

module.exports = function Authorization_admin(req, res, next) {
    const orginalUrl = req._parsedUrl.pathname; //请求路径
    const ip = clientIp(req);
    //若是跨域请求  首先会有一个试探请求 OPTIONS
    if (req.method === 'OPTIONS') {
        res.json(Response.success(null));
    } else if (whiteList_admin.indexOf(orginalUrl) !== -1) { //登录白名单
        next();
        return;
    } else {
        if (req.headers.authorization) {
            const adminToken = req.headers.authorization;
            const flag = token_verify(adminToken);
            if (flag) {
                next();
                return;
            } else {
                logger().warn(`ip: ${ip} cannot logging admin,token has expired`);
                res.json(Response.identity_error(null));
            }
        } else {
            logger().error(`ip: ${ip} havenot token to visit admin`);
            res.json(Response.identity_none(null));
        }
    }
}